package com.example.spider.provider.why10w.deprecated.why10org.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import com.example.spider.provider.why10w.deprecated.why10org.task.Why10orgDetailTask;
import com.example.spider.provider.why10w.dto.WhyImageInfo;
import com.example.spider.provider.why10w.dto.WhyTaskResult;
import com.example.spider.task.SpiderResultHandler;
import lombok.extern.slf4j.Slf4j;
import org.shoulder.core.util.JsonUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理 why10org 详情页结果
 *
 * @author lym
 */
@Slf4j
//@Component
public class Why10orgDetailResultHandler implements SpiderResultHandler<Why10orgDetailTask, String> {

    /**
     * handle
     */
    @Override
    public void handle(Why10orgDetailTask task, String html) {
        log.debug("prepare handing Why10orgDetail:{}", task.getUrl());
        // 要解析的太多了，先截取期望部分，避免每次解析全部html
        String hasContentRegex = "id=\"f\"(.*?)id=\"g\"";
        List<String> contentStr = ReUtil.findAllGroup1(hasContentRegex, html);
        if (contentStr.isEmpty()) {
            // 结束了
            log.error("why10orgDetail invalid. Task:{}", task);
            return;
        }

        String content = contentStr.get(0);

        String id = ReUtil.findAllGroup1("http://www.10why.org/(.*?)\\.html", task.getUrl()).get(0);

        String title = task.getTitle();

        // 类别，可能多个
        String categoryRegex = "<a href=\"http://www.10why.org/.*?\" rel=\"category tag\">(.*?)</a>";
        List<String> categoryList = ReUtil.findAllGroup1(categoryRegex, content);

        // 标签，可能多个
        String tagRegex = "rel=\"tag\">(.*?)</a>";
        List<String> tagList = ReUtil.findAllGroup1(tagRegex, content);

        // 文章
        String contentRegex = "<div class=\"n_n\">(.*?)<div class=\"quote\">";
        List<String> contentFindResult = ReUtil.findAllGroup1(contentRegex, content);
        String realContent = "";
        if (CollectionUtils.isEmpty(contentFindResult)) {
            // 不存在
            log.error("empty");
        } else {
            realContent = contentFindResult.get(0).trim();
        }

        // 图片，可能多个
        List<WhyImageInfo> imageInfoList = new ArrayList<>();
        List<String> imageMatchList = ReUtil.findAllGroup1("<img (.*?)>", realContent);
        if (!CollectionUtils.isEmpty(imageMatchList)) {
            for (String s : imageMatchList) {
                String name = ReUtil.findAllGroup1("alt=\"(.*?)\"", s).get(0);
                String url = ReUtil.findAllGroup1("src=\"(.*?)\"", s).get(0);
                WhyImageInfo imageInfo = WhyImageInfo.builder()
                        .name(name)
                        .url(url)
                        .build();
                imageInfoList.add(imageInfo);
            }
        }

        WhyTaskResult result = WhyTaskResult.builder()
                .id(id)
                .title(title)
                .url(task.getUrl())
                .categoryList(categoryList)
                .tagList(tagList)
                .imageInfoList(imageInfoList)
                .content(realContent)
                .build();
        // ***********************

        // 保存到文件
        String fileName = "F:/spider/www.10why.org/" + id + ".json";
        log.debug("prepare save to file: {}" + fileName);
        File file = FileUtil.touch(fileName);
        FileUtil.writeString(JsonUtils.toJson(result), file, StandardCharsets.UTF_8);

        String htmlFileName = "F:/spider/www.10why.org/" + id + ".html";
        log.debug("prepare save to file: {}" + fileName);
        File htmlFile = FileUtil.touch(htmlFileName);
        FileUtil.writeString(html, htmlFile, StandardCharsets.UTF_8);

        log.info("finished handle {} {} ", task.getClass().getSimpleName(), task.getUrl());
    }
}
